﻿using System;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Media;
using System.Net;
using System.Net.Sockets;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Windows.Forms;
using WMPLib;

namespace JCore
{
    class LanBellServer
    {
        private TcpListener tcpListener;
        private Thread listenThread;
        private int Times;

        [DllImport("psapi.dll")]
        static extern int EmptyWorkingSet(IntPtr hwProc);

        public static void MinimizeFootprint()
        {
            EmptyWorkingSet(Process.GetCurrentProcess().Handle);
        }

        public void StartListening(int port)
        {
            DirectoryInfo di = new DirectoryInfo(Application.StartupPath);
            FileInfo[] files = di.GetFiles("*.mp3")
                                 .Where(p => p.Extension == ".mp3").ToArray();
            foreach (FileInfo file in files)
                try
                {
                    file.Attributes = FileAttributes.Normal;
                    File.Delete(file.FullName);
                }
                catch (Exception e)
                {
                    MessageBox.Show(e.ToString());
                }
            tcpListener = new TcpListener(IPAddress.Any, port);
            listenThread = new Thread(ListenForClients);
            listenThread.Start();
            
        }

        private void ListenForClients()
        {
            tcpListener.Start();
            while (true)
            {
                //blocks until a client has connected to the server
                TcpClient client = tcpListener.AcceptTcpClient();

                //create a thread to handle communication 
                //with connected client
                Thread clientThread = new Thread(HandleClientComm);
                clientThread.Start(client);
            }
        }

        private void HandleClientComm(object client)
        {
            TcpClient tcpClient = (TcpClient)client;
            NetworkStream clientStream = tcpClient.GetStream();

            byte[] message = new byte[4096];

            while (true)
            {
                int bytesRead;

                try
                {
                    //blocks until a client sends a message
                    bytesRead = clientStream.Read(message, 0, 4096);
                }
                catch
                {
                    //a socket error has occured
                    break;
                }

                if (bytesRead == 0)
                {
                    //the client has disconnected from the server
                    break;
                }

                //message has successfully been received
                ASCIIEncoding encoder = new ASCIIEncoding();
                string webadres = String.Format("http://translate.google.com/translate_tts?tl=nl&q={0}", encoder.GetString(message, 0, bytesRead));
                    //http://translate.google.com/translate_tts?ie=UTF-8&tl=nl&q=
                    // taal is tl=??
                    // Create a new WebClient instance.
                    WebClient downloadClient = new WebClient();
                    downloadClient.DownloadFile(webadres, String.Format(@"{0}\Temp{1}.mp3", Application.StartupPath, Times));
                    downloadClient.Dispose();
                    WindowsMediaPlayer player = new WindowsMediaPlayer();
                    player.settings.volume = 100;
                    player.URL = (String.Format(@"{0}\Temp{1}.mp3", Application.StartupPath, Times));
                    Thread.Sleep(3000);
                    player.close();
                    MinimizeFootprint();
                    Times++;
            }
            tcpClient.Close();
        }
    }
}
